<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <todo-header :list="list" @addTask="addTaskHandler"></todo-header>
    <todo-main @delTask="delTaskHandler" :list="newList"></todo-main>
    <todo-footer
      @clearTask="clearTaskHandler"
      @changeTask="changeTaskHandler"
      :list="newList"
    ></todo-footer>
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list') || '[]'),
      all: "",
    };
  },
  methods: {
    addTaskHandler(txt) {
      let id =
        this.list.length <= 0 ? 100 : this.list[this.list.length - 1].id + 1;
      this.list.push({
        id,
        name: txt,
        isDone: false,
      });
    },
    delTaskHandler(id) {
      let index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    changeTaskHandler(val) {
      this.all = val;
    },
    clearTaskHandler() {
      this.list = this.list.filter((item) => item.isDone === false);
    },
  },
  computed: {
    newList() {
      if (this.all === "yes") {
        return this.list.filter((item) => item.isDone);
      } else if (this.all === "no") {
        return this.list.filter((item) => !item.isDone);
      } else {
        return this.list;
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("list", JSON.stringify(this.list));
      },
    },
  },
};
</script>